#!/usr/bin/env python
# -*- coding:utf-8 -*-

'how to usage ftplib'

__author__='zhaoxp'

import ftplib
import contextlib


HOST_IP='10.99.244.119'
PORT=21
TIME_OUT=5
USERNAME='wcadmin'
PASSWORD='2w3e$R%T9'
BUF_SIZE=1024


@contextlib.contextmanager
def ftp_context(host,port,user,passwd,debuglevel=0):
    try:
        ftp=ftplib.FTP()
        ftp.set_debuglevel(debuglevel)
        ftp.connect(host=host,port=port,timeout=TIME_OUT)
        ftp.login(user=user,passwd=passwd)
        yield ftp
    except ftplib.all_errors as ftp_errors:
        print('ftplib errors: %s , type of error: %s'%(ftp_errors,type(ftp_errors)))
        yield None
    if ftp:
        ftp.quit()

def usage_show():
    ftp=ftplib.FTP()
    ftp.set_debuglevel(1) # 0: nothing ; 1: moderate mount of debugging output; 2: maximum amount of debugging output
    ftp.connect(host=HOST_IP,port=PORT,timeout=TIME_OUT)
    ftp.login(user=USERNAME,passwd=PASSWORD)
    ftp.getwelcome()
    ftp.pwd()
    ftp.dir()
    ftp.mkd('tmpdir')
    ftp.dir()
    ftp.rmd('tmpdir')
    ftp.dir()
    ftp.size('/etc/hosts')
    ftp.quit()


def ftp_download_file():
    with ftp_context(host=HOST_IP,port=PORT,user=USERNAME,passwd=PASSWORD,debuglevel=0) as ftp:
        filename='/etc/hosts'
        result = ftp.retrbinary('RETR '+filename,open('download.txt','wb').write,BUF_SIZE)
        print 'result----------------',type(result),result


def ftp_upload_file():
    with ftp_context(host=HOST_IP,port=PORT,user=USERNAME,passwd=PASSWORD,debuglevel=0) as ftp:
        filename='/home/wcadmin/test.txt'
        result=ftp.storbinary('STOR '+filename,open('download.txt','rb'),BUF_SIZE)
        print 'result----------------',type(result),retult



if __name__=='__main__':
    print('show how to use ftplib')
    #usage_show()
    print('---------- start donwload file ----------')
    ftp_download_file()
    #print('---------- start upload file ----------')
    #ftp_upload_file()